<?php

namespace App\Helpers;

class Audit
{

    /**
     * 图片审核
     * @param $img
     * @return mixed
     */
    public function image($img)
    {
        $token = $this->url();
        $token = json_decode($token, true);
        $token = $token['access_token'];
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=' . $token;
        $img = file_get_contents($img);
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img
        );
        $res = $this->request_post($url, $bodys);
        $pic = json_decode($res, true);
        return $pic;
    }


    /**
     * 文本审核
     * @param $text
     * @return mixed
     */
    public function text($text){
        $token = $this->url();
        $token = json_decode($token, true);
        $token = $token['access_token'];
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token;
        $bodys = array(
            'text' => $text
        );
        $res = $this->request_post($url, $bodys);
        $text = json_decode($res, true);
        return $text;
    }

    /**
     * 发起http post请求(REST API), 并获取REST请求的结果
     * @param string $url
     * @param string $param
     * @return - http response body if succeeds, else false.
     */
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }

    /**
     * 请求路由
     * @return bool|string
     */
    public function url()
    {
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type'] = 'client_credentials';
        $post_data['client_id'] = 'WNyOCRSi89MwTPs2dgrQ5gvF';
        $post_data['client_secret'] = 'e5tzt7hUw8yVZKEnUcwr5fSQDmQPDe10';
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);

        $res = $this->request_post($url, $post_data);

        return $res;

    }
}
